package com.ltu.util.http;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import lombok.extern.slf4j.Slf4j;



/**
 * HTTPClient 工具类
 * 
 * @author Lynch 2014-09-15
 *
 */
@Slf4j
public class HttpClientUtil2 { 

	
	/**
	 * 发送http请求
	 * @param
	 * 		 url:请求地址
	 * @param
	 * 		 reqParams ： 请求参数信息
	 * @param
	 *       method ： POST, GET ...
	 * create by zjh 2016年2月16日  下午1:24:26
	 */
	public static String sendHTTPRequest(String url, ReqParams reqParams, String method) {

		HttpClient httpClient = getClient(url.startsWith("https") ? true : false);
		 
		String responseContent = null;
		try {

			HttpResponse response = null;

			if (method.equals(HTTPMethod.METHOD_POST)) {
				HttpPost httpPost = new HttpPost(url);

				RequestBindDataUtil.bindDataToRequest(httpPost, reqParams);

				response = httpClient.execute(httpPost);
			} else if (method.equals(HTTPMethod.METHOD_PUT)) {
				HttpPut httpPut = new HttpPut(url);
				
				RequestBindDataUtil.bindDataToRequest(httpPut, reqParams);

				response = httpClient.execute(httpPut);
			} else if (method.equals(HTTPMethod.METHOD_GET)) {

				HttpGet httpGet = new HttpGet(url);

				RequestBindDataUtil.bindDataToRequest(httpGet, reqParams);
				
				response = httpClient.execute(httpGet);

			} else if (method.equals(HTTPMethod.METHOD_DELETE)) {
				HttpDelete httpDelete = new HttpDelete(url);

				RequestBindDataUtil.bindDataToRequest(httpDelete, reqParams);
				response = httpClient.execute(httpDelete);
			}

			if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
				HttpEntity entity = response.getEntity();
				if (null != entity) {
					responseContent = EntityUtils.toString(entity, "UTF-8");
					EntityUtils.consume(entity);
				}
			}
			
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			httpClient.getConnectionManager().shutdown();
		}

		return responseContent;
	}

	 
	/**
	 * DownLoadFile whit Jersey
	 * create by zjh 2016年2月16日  下午5:35:21
	 */
	public static File downLoadFile(String url, ReqParams reqParams, File localPath) {
		
		HttpClient httpClient = getClient(url.startsWith("https") ? true : false);

		try {

			HttpGet httpGet = new HttpGet(url);

			RequestBindDataUtil.bindDataToRequest(httpGet, reqParams);

            HttpResponse response = httpClient.execute(httpGet);

			HttpEntity entity = response.getEntity();
			InputStream in = entity.getContent();
			FileOutputStream fos = new FileOutputStream(localPath);
			byte[] buffer = new byte[1024];
			int len1 = 0;
			while ((len1 = in.read(buffer)) != -1) {
				fos.write(buffer, 0, len1);
			}
			fos.close();

		} catch (Exception e) {
			throw new RuntimeException();
		} finally {
			httpClient.getConnectionManager().shutdown();
		}

		return localPath;
	}

	/**
	 * Create a httpClient instance
	 * 
	 * @param isSSL
	 * @return HttpClient instance
	 */
	public static HttpClient getClient(boolean isSSL) {

		HttpClient httpClient = new DefaultHttpClient();
		if (isSSL) {
			X509TrustManager xtm = new X509TrustManager() {
				public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
				}

				public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
				}

				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}
			};

			try {
				SSLContext ctx = SSLContext.getInstance("TLS");

				ctx.init(null, new TrustManager[] { xtm }, null);

				SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);

				httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory));

			} catch (Exception e) {
				throw new RuntimeException();
			}
		}

		return httpClient;
	}

//	public static URL getURL(String path) {
//		URL url = null;
//		String schema = "https";
//		String serviceHost = "a1.easemob.com";
//		try {
////			url = new URL(Constants.API_HTTP_SCHEMA, Constants.API_SERVER_HOST, "/" + path);
//			url = new URL(schema, serviceHost, "/" + path);
//		} catch (MalformedURLException e) {
//			e.printStackTrace();
//		}
//		return url;
//	}

	/**
	 * Check illegal String
	 * 
	 * @param regex
	 * @param str
	 * @return
	 */
	public static boolean match(String regex, String str) {
		//TODO
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(str);

		return matcher.lookingAt();
	}


	/**
	 * 发送json字符串
	 *
	 * @param url
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	public static String sendJsonData(String url, final String jsonStr) throws Exception {
		HttpClient httpClient = HttpClients.createDefault();
		HttpPost post = new HttpPost(url);
		post.addHeader("Content-type", "application/json; charset=utf-8");
		post.setHeader("Accept", "application/json");
		post.setEntity(new StringEntity(jsonStr, Charset.forName("UTF-8")));
		HttpResponse response = httpClient.execute(post);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			HttpEntity entity = response.getEntity();
			String resutlStr = EntityUtils.toString(entity, "UTF-8");
			return resutlStr;
		}
		return null;
	}

	
	
	public static void printRequestInfo(HttpServletRequest request) {
		log.info("request全文：\n"+request.toString());
		String headVal = request.getHeader("Host");

		log.info("Host:" + headVal);

		Enumeration<String> headNames = request.getHeaderNames();
		log.info("请求头：\n");
		while (headNames.hasMoreElements()) {

			String headName = headNames.nextElement();

			log.info(headName + ":" + request.getHeader(headName));

		}
		log.info("请求方式：\n"+request.getMethod());
		log.info("请求主体1：\n"+request.getServletContext().toString());
		log.info("请求主体2：\n"+request.getServletContext().getServerInfo());
		Enumeration<String> e = request.getParameterNames();
		StringBuilder keys = new StringBuilder("");
		log.info("请求参数：\n");
		while (e.hasMoreElements()) {
			String key = e.nextElement();
			log.info("\n" + key + ":" + request.getParameter(key));
		}

	}
	
}
